package com.cracker.websocket.server.service;

import com.cracker.websocket.server.entity.UserEntity;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.websocket.Session;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

/**
 * session服务,负责记录session-用户id映射关系,用于查找用户
 */
@Service
@Data
@Slf4j
public class SessionService {
    @Autowired
    private StatService statService;
    private ConcurrentHashMap<Integer, Session> onlineSession = new ConcurrentHashMap<>();

    public void sessionOnline(Session session, UserEntity userEntity) {
        session.getUserProperties().put("freshTime", new Date());
        onlineSession.put(userEntity.getId(), session);
    }

    public void sessionOffline(Session session) {
        int id = ((UserEntity) session.getUserProperties().get("user")).getId();
        if (null != onlineSession.get(id)) {
            onlineSession.remove(id);
        }
    }

    /**
     * 刷新用户最后通讯时间
     */
    public void freshUser(Session session) {
        session.getUserProperties().put("freshTime", new Date());
        UserEntity userEntity = (UserEntity) session.getUserProperties().get("user");
        if (null != userEntity) {
            onlineSession.put(userEntity.getId(), session);
        }
    }

    public Session getByUserId(int userId) {
        return onlineSession.get(userId);
    }
}
